package com.icinfo.cloud.provider.punish.fastcase.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.CertTypeEnum;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.RecordSaveTypeEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.CustomCheckParamUtil;
import com.icinfo.cloud.provider.peripheralinterface.regulatory.service.IRegulatoryService;
import com.icinfo.cloud.provider.peripheralinterface.regulatory.vo.PunishItemVo;
import com.icinfo.cloud.provider.punish.common.documentdataload.dto.CasePartiesQueryDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.RebuildDocumentDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamMainMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamMain;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigFastCaseMattersService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigFastCaseMattersVo;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.fasecase.dto.FastNoticeDocumentDto;
import com.icinfo.cloud.provider.punish.fastcase.dto.*;
import com.icinfo.cloud.provider.punish.fastcase.enums.SimpleFormTypeEnum;
import com.icinfo.cloud.provider.punish.fastcase.enums.StepOperateEnum;
import com.icinfo.cloud.provider.punish.fastcase.service.IFastCaseRegisterService;
import com.icinfo.cloud.provider.punish.fastcase.vo.FastAutoCloseCaseReminderVo;
import com.icinfo.cloud.provider.punish.fastcase.vo.FastCaseNoticeDocumentVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStageEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.*;
import com.icinfo.cloud.provider.punish.ucase.caseregister.service.ICaseRegisterService;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentResultRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentResultRecordService;
import com.icinfo.cloud.workflow.config.mapper.ConfigWorkFlowDetailInfoMapper;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowDetailInfo;
import com.icinfo.cloud.workflow.work.service.IWorkFlowRollBusiDetailService;
import com.icinfo.cloud.workflow.work.service.IWorkFlowRollInfoChangeService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author cds
 * @date 2022/12/6
 * @since 汇信科技
 */
@Slf4j
@Service
@AllArgsConstructor
public class FastCaseRegisterServiceImpl implements IFastCaseRegisterService {

    private final CaseMainInfoMapper caseMainInfoMapper;

    private final IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    private final IStageDocCommonOperateService stageDocCommonOperateService;

    private final CaseDocumentRecordMapper caseDocumentRecordMapper;

    private final ICasePartiesRecordService casePartiesRecordService;

    private final ICaseReasonMainRecordService caseReasonMainRecordService;

    private final ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICasePartiesLegalInfoService casePartiesLegalInfoService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ConfigWorkFlowDetailInfoMapper configWorkFlowDetailInfoMapper;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ConfigBusiParamMainMapper configBusiParamMainMapper;
    @Resource
    private IWorkFlowRollInfoChangeService workFlowRollInfoChangeService;
    @Resource
    private IWorkFlowRollBusiDetailService workFlowRollBusiDetailService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ICaseRegisterService caseRegisterService;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private ICasePartiesPersonInfoService casePartiesPersonInfoService;
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private ICasePaymentResultRecordService casePaymentResultRecordService;
    @Resource
    private ICaseRelatedDocumentRecordService caseRelatedDocumentRecordService;
    @Resource
    private ICaseOfflineDocumentRecordService caseOfflineDocumentRecordService;
    @Resource
    private IConfigFastCaseMattersService configFastCaseMattersService;
    @Resource
    private IRegulatoryService regulatoryService;
    /**
     * 速结告知书生成
     *
     * @param dto
     * @return
     */
    @Override
    public FastNoticeDocumentDto generateFastNoticeDocument(CaseRegisterDetailQueryDto dto) {
        String caseId = dto.getCaseId();
        log.info("==> 速结告知书生成,入参：{}", caseId);
        CaseMainInfo oldCaseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (Objects.isNull(oldCaseMainInfo)) {
            throw new BusinessException("该案件不存在");
        }

        UserDTO userInfo = UserUtil.getUserInfo();
        //获取速结或快办告知书目录编码
        String documentCatalogCodeOfSJGZS = caseDocumentRecordService.getDocumentCatalogCodeOfSJGZS(userInfo.getAreaCode(), oldCaseMainInfo.getBusiParamId());

        // 若已存在生成的文书直接查询返回
        /*FastNoticeDocumentDto record = this.getNewestValidRecord(caseId, configBusiParam.getDocumentCatalogCode());
        if (Objects.nonNull(record)) {
            record.setDocumentCatalogCode(configBusiParam.getDocumentCatalogCode());
            return record;
        }*/

        // 组装参数 生成文书
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        commonOperateSaveDto.setCaseId(caseId);
        commonOperateSaveDto.setDocumentCatalogCode(documentCatalogCodeOfSJGZS);
        commonOperateSaveDto.setIsUpdateRelationTable(Constant.STRING_0);
        // TODO: 2022/12/6 签名数据 补充
        HashMap<String, Object> dataMap = this.buildParams(oldCaseMainInfo);
        commonOperateSaveDto.setDataMap(dataMap);
        log.info("==> 文书生成公共方法start,入参{}", JSONUtil.toJsonStr(commonOperateSaveDto));
        Map<String, Object> docResultMap = stageDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
        log.info("==> 文书生成公共方法end,出参：{}", JSONUtil.toJsonStr(docResultMap));

        // 查询返回生成的文书url
        FastNoticeDocumentDto newestValidRecord = this.getNewestValidRecord(caseId, documentCatalogCodeOfSJGZS);
        newestValidRecord.setDocumentCatalogCode(documentCatalogCodeOfSJGZS);
        return newestValidRecord;
    }

    /**
     * 构建 速结告知文书生成参数
     *
     * @param caseMainInfo
     * @return
     */
    private HashMap<String, Object> buildParams(CaseMainInfo caseMainInfo) {
        // 案件编号，立案案号
        HashMap<String,Object> params = new HashMap<>(8);
        // 机构文书抬头标准名称
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode(), caseMainInfo.getCaseDeptCode());
        params.put("orgStandardName",sysDepartParam.getOrgStandardName());
        params.put("caseNumber",caseMainInfo.getCaseNumber());
        // 当事人
        List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(caseMainInfo.getId());
        for (CasePartiesRecordVo casePartiesRecord : casePartiesInfo) {
            if(Constant.STRING_1.equals(casePartiesRecord.getPartyType())){
                params.put("partiesPerson",casePartiesRecord.getPartyName());
                params.put("partyInfo", "姓名：" + casePartiesRecord.getPartyName() + "，" + CertTypeEnum.getValueByCode(casePartiesRecord.getPartyIdentityType()) + "：" + casePartiesRecord.getPartyIdentityCode());
            }else {
                //法人当事人显示法定代表人名称
                CasePartiesLegalInfoVo legalInfo = casePartiesLegalInfoService.getCasePartiesLegalInfo(casePartiesRecord.getPartyId());
                if(ObjectUtil.isNotEmpty(legalInfo)){
                    params.put("partiesPerson",legalInfo.getLegalName());
                    params.put("partyInfo", "单位名称：" + legalInfo.getEntName() + "，统一信用代码：" + legalInfo.getUniscid());
                }

            }
        }
        LocalDateTime caseCreateTime = caseMainInfo.getCaseCreateTime();
        String formatTime = caseCreateTime.format(DateTimeFormatter.ofPattern(DatePattern.CHINESE_DATE_PATTERN));
        params.put("caseHappenTime",formatTime);
        // 案由
        CaseReasonMainRecordVo caseReason = caseReasonMainRecordService.getCaseReasonRecordByCaseId(caseMainInfo.getId());
        if(Objects.nonNull(caseMainInfo)){
            params.put("caseReason",caseReason.getCaseReasonName());
        }
        // 执法人员
        List<CaseHandlePersonRecord> caseHandlePersons = caseHandlePersonRecordService.getCaseHandlePersonRecordList(caseReason.getCaseId());
        if(CollUtil.isNotEmpty(caseHandlePersons)){
            for (CaseHandlePersonRecord caseHandlePerson : caseHandlePersons) {
                if(Constant.STRING_1.equals(caseHandlePerson.getHandlePersonType())){
                    params.put("mainCaseHandlePerson",caseHandlePerson.getHandlePersonName());
                    params.put("mainCert",caseHandlePerson.getLawEnforcementCert());
                    continue;
                }
                if(Constant.STRING_2.equals(caseHandlePerson.getHandlePersonType())){
                    params.put("assisCaseHandlePerson",caseHandlePerson.getHandlePersonName());
                    params.put("assisCert",caseHandlePerson.getLawEnforcementCert());
                }
            }
        }
        if (!caseMainInfo.getCaseAreaCode().contains(Constant.STRING_AREA_CODE_ANJI)) {
            params.put("signFingerprintDate", BaseUtil.getNowDate());
        }
        // signFingerprintPic 签名 signFingerprintDate 签名时
        return params;
    }

    /**
     * 获取最新有效的速结告知书
     *
     * @param caseId
     * @return
     */
    private FastNoticeDocumentDto getNewestValidRecord(String caseId, String catalogCode) {
        CaseDocumentRecord record = caseDocumentRecordMapper.getNewestValidRecord(caseId, catalogCode);
        if (Objects.isNull(record)) {
            return null;
        }
        FastNoticeDocumentDto resultDto = new FastNoticeDocumentDto();
        resultDto.setCaseId(caseId);
        resultDto.setDocumentId(record.getId());
        resultDto.setDocumentUrl(record.getDocumentUrl());
        resultDto.setDocumentCreateTime(record.getDocumentCreateTime());
        return resultDto;
    }

    /**
     * 【AJ-V1.1.1】描述： 速结程序转普通程序
     *
     * @author: zhengqiang
     * @date: 2023/3/8
     * @param: caseId
     * @return {@link Result}
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result changeToNormalProcedure(String caseId) {
        //允许转普通程序阶段
        List allowStageList = Arrays.asList(CaseStageEnum.INVESTIGATION.getCode(),
                CaseStageEnum.PUNISH_INFORM.getCode(), CaseStageEnum.PUNISH_DECIDE.getCode());
        //查询案件信息
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        if (ObjectUtil.isEmpty(caseMainInfo)) {
            throw new BusinessException("案件不存在");
        }
        //校验案件状态
        if (caseMainInfoService.validateCaseIsInNotDealStatus(caseMainInfo, null)) {
            throw new BusinessException("当前案件状态不允许进行该操作");
        }
        //校验案件阶段
        if (!allowStageList.contains(caseMainInfo.getCaseCurrentStageCode())) {
            throw new BusinessException("当前案件阶段不允许进行该操作");
        }
        //判断是否速结程序
        if (!CaseTypeEnum.SIMPLE_QUICK.getCode().equals(caseMainInfo.getCaseType())
                && !CaseTypeEnum.FAST_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
            throw new BusinessException("非快办流程不能转正常程序");
        }

        String flowCode = caseMainInfo.getCaseFlowCode();
        String flowVersion = caseMainInfo.getCaseFlowVersion();
        //查询调查取证阶段工作流
        List<ConfigWorkFlowDetailInfo> configWorkFlowDetailInfos = workFlowRollInfoChangeService.getConfigWorkFlowDetailInfoList(flowCode, flowVersion, Arrays.asList(CaseStageEnum.INVESTIGATION.getCode()), null);
        if (ObjectUtil.isEmpty(configWorkFlowDetailInfos)) {
            throw new BusinessException("获取工作流配置异常");
        }
        String investigationLinkCode = configWorkFlowDetailInfos.get(0).getWorkLinkCode();
        if (!CaseStageEnum.INVESTIGATION.getCode().equals(caseMainInfo.getCaseCurrentStageCode())) {
            //非调查取证阶段
            //1.撤回到调查取证
            caseMainInfoService.doRecallCaseHandleLink(caseId, investigationLinkCode);
        } else {
            //撤回文书
            workFlowRollBusiDetailService.doDealBusiDataStatusWithWorkLinkRecall(caseId, null, investigationLinkCode);
        }

        //更新案件工作流数据
        ConfigBusiParamMain configBusiParamMain = configBusiParamMainMapper.selectByPrimaryKey(caseMainInfo.getBusiParamId());
        String changeCaseFlowCode = configBusiParamMain.getRelationWorkflowId();
        //更新变更后的工作流数据
        workFlowRollInfoChangeService.doDealWorkFlowRollInfoChangeData(caseId, changeCaseFlowCode);

        //删除调查取证阶段证据
        //evidenceInventoryService.deleteEvidenceByCaseId(caseId);
        return Result.success(Constant.STRING_SUCCESS_EN);
    }

    /**
     * 【V1.11.4】描述： 修改简案快办立案(处罚告知流程)相关文书
     *
     * @author: zhengqiang
     * @date: 2023/4/20
     * @param: modifyOfRegisterDto
     * @return {@link Result}
     **/
    @Transactional(rollbackFor = {Error.class, Exception.class})
    @Override
    public Result modifyFastCaseRegisterDocuments(FastCaseDocumentModifyOfRegisterDto modifyOfRegisterDto) {
        //立案审批表, 调查终结报告, 处罚告知审批表,处罚告知书, 不予处罚审批表及不予处罚告知书
        List ModifyKindCodeList = Arrays.asList(DocumentKindEnum.DOC_KIND_ZJBG.getCode(),
                DocumentKindEnum.DOC_KIND_CFGZSPB.getCode(), DocumentKindEnum.DOC_KIND_CFGZS.getCode(),
                DocumentKindEnum.DOC_KIND_DK1BYCFGZSPB.getCode(), DocumentKindEnum.DOC_KIND_DK2BYXZCFGZS.getCode());

        String caseId = modifyOfRegisterDto.getCaseId();
        //1.处理立案审批表
        FastCaseDocumentRecordModifyDto modifyDtoLASPB = modifyFastCaseRegisterData(modifyOfRegisterDto);
        modifyFastCaseDocumentRecord(modifyDtoLASPB);
        //查询需要修改的文书
        CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
        queryDto.setCaseId(caseId);
        List<CaseDocumentRecordDto> documentRecordDtoList = caseDocumentRecordService.getDocumentRecordDtoList(queryDto);
        if (ObjectUtil.isNotEmpty(documentRecordDtoList)) {
            for (CaseDocumentRecordDto recordDto : documentRecordDtoList) {
                String documentKindCode = recordDto.getDocumentKindCode();
                String documentCatalogCode = recordDto.getDocumentCatalogCode();
                FastCaseDocumentRecordModifyDto modifyDto = null;
                if (ModifyKindCodeList.contains(documentKindCode)) {
                    //重新生成涉及变动的文书
                    //调查终结报告, 处罚告知审批表, 不予处罚审批表及不予处罚告知书
                    modifyDto = buildDocumentModifyData(caseId, documentKindCode, documentCatalogCode);
                }
                if (ObjectUtil.isNotEmpty(modifyDto)) {
                    modifyFastCaseDocumentRecord(modifyDto);
                }
            }
        }
        return Result.success(Constant.STRING_SUCCESS_EN);
    }

    /**
     * 描述： 更新立案相关数据
     *
     * @author: zhengqiang
     * @date: 2023/4/20
     * @param: saveDto
     * @return {@link boolean}
     **/
    private FastCaseDocumentRecordModifyDto modifyFastCaseRegisterData(FastCaseDocumentModifyOfRegisterDto modifyOfRegisterDto) {
        CaseRegisterSaveDto saveDto = new CaseRegisterSaveDto();
        BeanUtils.copyProperties(modifyOfRegisterDto, saveDto);
        //校验保存参数
        String errorMsg =  caseRegisterService.checkAndDealCaseRegisterInfo(saveDto);
        if (StringUtils.isNotEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        String caseId = saveDto.getCaseId();
        //更新当事人信息
        String partyName = "";
        CasePartiesRecordQueryDto partiesRecordQueryDto = new CasePartiesRecordQueryDto();
        partiesRecordQueryDto.setIsQueryInvalidData(YesOrNoEnum.NO.getCode());
        partiesRecordQueryDto.setCaseId(caseId);
        List<CasePartiesInfoVo> casePartiesInfoVos = casePartiesRecordMapper.selectCasePartiesInfoList(partiesRecordQueryDto);
        if (ObjectUtil.isNotEmpty(casePartiesInfoVos)) {
            //简案快办只支持单当事人,取第一条
            CasePartiesInfoVo casePartiesInfoVo = casePartiesInfoVos.get(0);
            partyName = casePartiesInfoVo.getPartyName();
            String recordId = casePartiesInfoVo.getId();
            String partyId = casePartiesInfoVo.getPartyId();
            if (PartyTypeEnum.LEGAL.getCode().equals(casePartiesInfoVo.getPartyType())) {
                //更新法人当事人 -- 当事人证件类型、名称/姓名、证件号不允许修改
                for (CaseRegisterPartiesLegalInfoDto legalInfoDto : saveDto.getPartiesLegalInfoList()) {
                    legalInfoDto.setId(partyId);
                    CasePartiesLegalInfoDto casePartiesLegalInfo = new CasePartiesLegalInfoDto();
                    BeanUtils.copyProperties(legalInfoDto, casePartiesLegalInfo);
                    casePartiesLegalInfo.setAddress(legalInfoDto.getUnitAddress());
                    casePartiesLegalInfo.setLegalName(legalInfoDto.getLegal());
                    casePartiesLegalInfo.setCaseId(caseId);
                    casePartiesLegalInfo.setLegalIndustryType(legalInfoDto.getLegalIndustryType());
                    casePartiesLegalInfo.setOperateType(RecordSaveTypeEnum.MOD.getCode());
                    casePartiesLegalInfoService.saveCasePartiesLegalInfo(casePartiesLegalInfo);

                    //更新当事人表
                    CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
                    casePartiesRecord.setCaseId(saveDto.getCaseId());
                    casePartiesRecord.setId(recordId);
                    casePartiesRecord.setPartyId(partyId);
                    casePartiesRecord.setCreateTime(LocalDateTime.now());
                    casePartiesRecordMapper.updateByPrimaryKeySelective(casePartiesRecord);
                }
            } else {
                for (CaseRegisterPartiesPersonInfoDto personInfoDto : saveDto.getPartiesPersonInfoList()) {
                    //更新当事人信息 -- 当事人证件类型、名称/姓名、证件号不允许修改
                    personInfoDto.setId(partyId);
                    CasePartiesPersonInfoDto casePartiesPersonInfo = new CasePartiesPersonInfoDto();
                    BeanUtils.copyProperties(personInfoDto, casePartiesPersonInfo);
                    casePartiesPersonInfo.setCaseId(caseId);
                    casePartiesPersonInfo.setOperateType(RecordSaveTypeEnum.MOD.getCode());
                    String[] addressAreas = personInfoDto.getAddressAreas();
                    if (ArrayUtil.isNotEmpty(addressAreas)) {
                        casePartiesPersonInfo.setAddressAreasStr(String.join(",", addressAreas));
                    }
                    casePartiesPersonInfoService.saveCasePartiesPersonInfo(casePartiesPersonInfo);

                    //更新当事人表
                    CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
                    casePartiesRecord.setCaseId(saveDto.getCaseId());
                    casePartiesRecord.setId(recordId);
                    casePartiesRecord.setPartyId(partyId);
                    casePartiesRecord.setAddressDetail(personInfoDto.getAddressDetail());
                    casePartiesRecord.setAddressAreas(String.join(",", personInfoDto.getAddressAreas()));
                    casePartiesRecord.setCreateTime(LocalDateTime.now());
                    casePartiesRecordMapper.updateByPrimaryKeySelective(casePartiesRecord);
                }
            }
        }

        //处理案由信息(违则,罚则可修改)
        //之前老数据更新为失效
        /*Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        List<CaseReasonMainRecord> recordList = caseReasonMainRecordMapper.selectByExample(example);
        if (recordList != null && recordList.size() > 0) {
            for (CaseReasonMainRecord record : recordList) {
                record.setStatus(Constant.STRING_0);
                caseReasonMainRecordMapper.updateByPrimaryKey(record);
            }
        }
        List<CaseReasonInfoDto> caseReasonInfoList = saveDto.getCaseReasonInfoList();
        if (ObjectUtil.isNotEmpty(caseReasonInfoList)) {
            for (CaseReasonInfoDto caseReasonInfoDto : caseReasonInfoList) {
                CaseReasonMainRecord caseReasonMainRecord = new CaseReasonMainRecord();
                BeanUtils.copyProperties(caseReasonInfoDto, caseReasonMainRecord);
                caseReasonMainRecord.setCreateTime(LocalDateTime.now());
                caseReasonMainRecord.setId(BaseUtil.createUid());
                caseReasonMainRecord.setCaseId(caseId);
                caseReasonMainRecord.setCaseReasonNameSimple(BaseUtil.handleCaseReason(caseReasonInfoDto.getCaseReasonName()));
                caseReasonMainRecord.setIllegalBasisFormat(BaseUtil.removeHtml(caseReasonInfoDto.getIllegalBasis()));
                caseReasonMainRecord.setIllegalDetailFormat(BaseUtil.removeHtml(caseReasonInfoDto.getIllegalDetail()));
                caseReasonMainRecord.setPunishBasisFormat(BaseUtil.removeHtml(caseReasonInfoDto.getPunishBasis()));
                caseReasonMainRecord.setPunishDetailFormat(BaseUtil.removeHtml(caseReasonInfoDto.getPunishDetail()));
                caseReasonMainRecord.setStatus(Constant.STRING_1);
                String nodeIds = "";
                for (String str : caseReasonInfoDto.getCaseReasonIds()) {
                    if (org.apache.commons.lang.StringUtils.isEmpty(nodeIds)) {
                        nodeIds = str;
                    } else {
                        nodeIds = nodeIds + "," + str;
                    }
                }
                caseReasonMainRecord.setCaseReasonNodeid(nodeIds);
                caseReasonMainRecordMapper.insertSelective(caseReasonMainRecord);
            }
        }*/

        //更新主表数据
        CaseMainInfo caseMainInfo = new CaseMainInfo();
        caseMainInfo.setId(saveDto.getCaseId());
        BeanUtils.copyProperties(saveDto, caseMainInfo);
        caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);

        //更新宽表数据
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        CaseMainDetailInfo oldDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(saveDto.getCaseId());
        updateCaseMainDetailInfo.setCaseId(caseId);
        updateCaseMainDetailInfo.setId(oldDetailInfo.getId());
        updateCaseMainDetailInfo.setCaseHappenTime(BaseUtil.stringToLocalDateTime(saveDto.getCaseHappenTime()));
        updateCaseMainDetailInfo.setCaseSourceId(saveDto.getCaseSourceId());
        updateCaseMainDetailInfo.setCaseHappenAddressDetail(saveDto.getCaseHappenAddress());
        updateCaseMainDetailInfo.setCaseHappenAddressAreaCode(saveDto.getCaseHappenAddressAreaCode());
        updateCaseMainDetailInfo.setCaseName(saveDto.getCaseName());
        updateCaseMainDetailInfo.setCaseConciseCondition(saveDto.getCaseConciseCondition());
        //案发经过
        String caseRegisterTimeStr = DateTimeFormatter.ofPattern("yyyy年M月d日").format(LocalDateTime.now());
        String caseHappenTime = DateTimeFormatter.ofPattern("yyyy年M月d日").format(updateCaseMainDetailInfo.getCaseHappenTime());
        String caseHappenAddressDetail = saveDto.getCaseHappenAddressDetail();
        String caseReasonName = "";
        List<CaseReasonMainRecordVo> caseReasonMainRecordVos = caseReasonMainRecordService.getCaseReasonRecordListByCaseId(caseId);
        if (ObjectUtil.isNotEmpty(caseReasonMainRecordVos)) {
            caseReasonName = caseReasonMainRecordVos.stream().map(CaseReasonMainRecordVo::getCaseReasonName).collect(Collectors.joining(","));
        }
        String caseHappenProcess = caseHappenTime + "，" + partyName + "在" + caseHappenAddressDetail + "实施" + caseReasonName
                + "的违法行为。执法人员对现场进行拍照勘察、取证。被勘验人对现场勘验情况无异议。本案于" + caseRegisterTimeStr + "立案，对" + partyName
                + "进行了调查询问。并于" + caseRegisterTimeStr + "结束案件调查。";
        updateCaseMainDetailInfo.setCaseHappenProcess(caseHappenProcess);
        updateCaseMainDetailInfo.setUpdateTime(LocalDateTime.now());
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);



        HashMap<String, Object> dataMap = BaseUtil.javaToMap(saveDto);
        FastCaseDocumentRecordModifyDto modifyDto = new FastCaseDocumentRecordModifyDto();
        modifyDto.setDocumentId(modifyOfRegisterDto.getDocumentId());
        modifyDto.setDataMap(dataMap);
        return modifyDto;
    }

    /**
     * 描述： 组装文书修改字段的数据
     *
     * @author: zhengqiang
     * @date: 2023/4/26
     * @param: caseId
     * @param: kindCode
     * @return {@link FastCaseDocumentRecordModifyDto}
     **/
    private FastCaseDocumentRecordModifyDto buildDocumentModifyData(String caseId, String kindCode, String documentCatalogCode) {
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode);
        if (ObjectUtil.isEmpty(caseDocumentRecord)) {
            return null;
        }
        HashMap<String, Object> dataMap = new HashMap<>();
        String caseRegisterTimeStr = DateTimeFormatter.ofPattern("yyyy年M月d日").format(LocalDateTime.now());
        /*//违则
        String illegalBasisFormat = null;
        //罚则
        String punishBasis = null;
        String punishBasisFormat = null;
        String illegalDetailFormat = null;
        String punishDetailFormat = null;
        List<CaseReasonMainRecordVo> caseReasonRecordList= caseReasonMainRecordService.getCaseReasonRecordListByCaseId(caseId);
        if (ObjectUtil.isNotEmpty(caseReasonRecordList)) {
            CaseReasonMainRecordVo caseReasonMainRecordVo = caseReasonRecordList.get(0);
            illegalBasisFormat = caseReasonMainRecordVo.getIllegalBasisFormat();
            punishBasis = caseReasonMainRecordVo.getPunishBasis();
            punishBasisFormat = caseReasonMainRecordVo.getPunishBasisFormat();
            illegalDetailFormat = caseReasonMainRecordVo.getIllegalDetailFormat();
            punishDetailFormat = caseReasonMainRecordVo.getPunishDetailFormat();
        }*/
        if (DocumentKindEnum.DOC_KIND_ZJBG.getCode().equals(kindCode)) {
            //立案信息修改会变更调查终结报告字段
            //案件名称, 调查开始时间, 调查结束时间, 案发经过, 当事人基本情况
            dataMap.put("AJDCZJBG_AY", caseMainInfo.getCaseName());
            dataMap.put("AJDCZJBG_DCKSSJ", caseRegisterTimeStr);
            dataMap.put("AJDCZJBG_DCJSSJ", caseRegisterTimeStr);

            //当事人基本情况
            String partyBasicInfo = null;
            List<CasePartiesInfoVo> casePartiesInfos = casePartiesRecordService.getCasePartiesInfoVo(caseId, caseDocumentRecord.getPartyId());
            if (ObjectUtil.isNotEmpty(casePartiesInfos)) {
                CasePartiesInfoVo casePartiesInfoVo = casePartiesInfos.get(0);
                if (PartyTypeEnum.PERSON.getCode().equals(casePartiesInfoVo.getPartyType())) {
                    partyBasicInfo = "姓名：" + casePartiesInfoVo.getPartyName()
                            + "，性别：" + casePartiesInfoVo.getSex()
                            + "，出生日期：" + casePartiesInfoVo.getBirth()
                            + "，公民身份号码：" + casePartiesInfoVo.getPartyIdentityCode()
                            + "，住所：" + casePartiesInfoVo.getAddress();
                } else {
                    partyBasicInfo = "企业名称：" + casePartiesInfoVo.getPartyName()
                            + "，统一社会信用代码：" + casePartiesInfoVo.getPartyIdentityCode()
                            + "，法定代表人：" + casePartiesInfoVo.getLegalName()
                            + "，住所：" + casePartiesInfoVo.getAddress();
                }
            }
            if (ObjectUtil.isNotEmpty(partyBasicInfo)) {
                dataMap.put("AJDCZJBG_DSRJBQK", partyBasicInfo);
            }
            /*//违则
            if (ObjectUtil.isNotEmpty(illegalBasisFormat)) {
                dataMap.put("AJDCZJBG_WZ", illegalBasisFormat);
            }
            //罚则
            if (ObjectUtil.isNotEmpty(punishBasis)) {
                dataMap.put("AJDCZJBG_FZ", punishBasis);
            }*/
            //案发经过
            dataMap.put("AJDCZJBG_AFJG", caseMainDetailInfo.getCaseHappenProcess());
        } else if (DocumentKindEnum.DOC_KIND_CFGZSPB.getCode().equals(kindCode)
                || DocumentKindEnum.DOC_KIND_DK1BYCFGZSPB.getCode().equals(kindCode)) {
            //处罚告知审批表或不予处罚告知审批表
            //案件名称, 案发地, 当事人列表
            dataMap.put("caseName", caseMainInfo.getCaseName());
            dataMap.put("caseHappenAddress", caseMainDetailInfo.getCaseHappenAddressDetail());
            String caseHappenTime = DateTimeFormatter.ofPattern("yyyy年M月d日").format(caseMainDetailInfo.getCaseHappenTime());
            dataMap.put("caseHappenTime", caseHappenTime);
            CasePartiesDetailInfoVo casePartiesDetailInfoByCaseIdAndPartyId = casePartiesRecordService.getCasePartiesDetailInfoByCaseIdAndPartyId(caseId, caseDocumentRecord.getPartyId());
            CasePartiesQueryDto casePartiesQueryDto = new CasePartiesQueryDto();
            casePartiesQueryDto.setCaseId(caseId);
            casePartiesQueryDto.setPartyId(caseDocumentRecord.getPartyId());
            casePartiesQueryDto.setPartyType(casePartiesDetailInfoByCaseIdAndPartyId.getPartyType());
            List<Map<String, Object>> casePartiesDetailInfoList = casePartiesRecordService.getCasePartiesDetailInfoList(casePartiesQueryDto);
            if (ObjectUtil.isNotEmpty(casePartiesDetailInfoList)) {
                Map<String, Object> stringObjectMap = casePartiesDetailInfoList.get(0);
                String partyType = stringObjectMap.get("partyType").toString();
                if (PartyTypeEnum.PERSON.getCode().equals(partyType)) {
                    dataMap.put("personInfoCycle", casePartiesDetailInfoList);
                } else {
                    dataMap.put("legalInfoCycle", casePartiesDetailInfoList);
                }
            }

        } else if (DocumentKindEnum.DOC_KIND_CFGZS.getCode().equals(kindCode)) {
            //处罚告知书
            //立案日期, 违则
            dataMap.put("CFGZS__LARQ", caseRegisterTimeStr);
            /*if (ObjectUtil.isNotEmpty(illegalBasisFormat)) {
                dataMap.put("CFGZS_WZ", illegalBasisFormat);
            }
            //罚则
            if (ObjectUtil.isNotEmpty(punishBasis)) {
                dataMap.put("CFGZS_AYFZ", punishBasis);
            }
            //违则
            if (ObjectUtil.isNotEmpty(illegalDetailFormat)) {
                dataMap.put("XZCFJDS_WZ", illegalDetailFormat);
            }
            //违则
            if (ObjectUtil.isNotEmpty(punishDetailFormat)) {
                dataMap.put("XZCFSXGZS_GDTWO", punishDetailFormat);
            }*/
        } else if (DocumentKindEnum.DOC_KIND_DK2BYXZCFGZS.getCode().equals(kindCode)) {
            //不予行政处罚告知书
            //立案日期
            dataMap.put("XZCFSXGZS__LARQ", caseRegisterTimeStr);
            /*if (ObjectUtil.isNotEmpty(illegalBasisFormat)) {
                dataMap.put("XZCFSXGZS_FZ", illegalBasisFormat);
            }
            //罚则
            if (ObjectUtil.isNotEmpty(punishBasisFormat)) {
                dataMap.put("XZCFSXGZS_AYFZ", punishBasisFormat);
            }
            //违则
            if (ObjectUtil.isNotEmpty(illegalDetailFormat)) {
                dataMap.put("XZCFJDS_WZ", illegalDetailFormat);
            }
            //违则
            if (ObjectUtil.isNotEmpty(punishDetailFormat)) {
                dataMap.put("XZCFJDS_FZ", punishDetailFormat);
            }*/

        }

        FastCaseDocumentRecordModifyDto modifyDto = new FastCaseDocumentRecordModifyDto();
        modifyDto.setDocumentId(caseDocumentRecord.getId());
        modifyDto.setDataMap(dataMap);
        return modifyDto;
    }

    /**
     * 【V1.11.4】描述： 简案快办待提交文书编辑通用方法
     *
     * @author: zhengqiang
     * @date: 2023/4/20
     * @param: modifyDto
     * @return
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyFastCaseDocumentRecord(FastCaseDocumentRecordModifyDto modifyDto) {
        CustomCheckParamUtil.doCheck(modifyDto);
        String originalDocument = modifyDto.getDocumentId();
        CaseDocumentRecord caseDocumentRecordInfo = caseDocumentRecordMapper.selectByPrimaryKey(originalDocument);
        if (ObjectUtil.isEmpty(caseDocumentRecordInfo)) {
            throw new BusinessException("文书记录不存在");
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        if (userInfo == null) {
            throw new BusinessException("未登录或登录信息已失效");
        }
        Map<String, Object> dataMap = modifyDto.getDataMap();
        // 文书记录修改变更的字段
        JSONObject jsonObject = JSON.parseObject(caseDocumentRecordInfo.getDocumentContent());
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if (ObjectUtil.isNotEmpty(dataMap.get(entry.getKey())) && entry.getValue() != null && !entry.getValue().equals(dataMap.get(entry.getKey()))){
                jsonObject.put(entry.getKey(), dataMap.get(entry.getKey()));
            }
        }
        //原文书内容没有的字段处理
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            if (!jsonObject.containsKey(entry) && ObjectUtil.isNotEmpty(dataMap.get(entry.getKey()))) {
                jsonObject.put(entry.getKey(), dataMap.get(entry.getKey()));
            }
        }
        //更新文书内容
        caseDocumentRecordInfo.setDocumentContent(jsonObject.toJSONString());
        caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecordInfo);

        //重新生成文书
        Map<String, Object> paramJson = new HashMap<>(8);

        RebuildDocumentDto dto = new RebuildDocumentDto(caseDocumentRecordInfo.getId(), "");
        List<RebuildDocumentDto> list = new ArrayList<>();
        list.add(dto);
        paramJson.put("documentInfo", list);
        Result<Map<String, Object>> result = stageDocCommonOperateService.rebuildPdf(paramJson);
        log.info("edit document,rebuild result :{}", result);
        int num = 0;
        if (ObjectUtil.isNotEmpty(result) && HttpStatus.HTTP_OK == result.getCode()) {
            num = (int) result.getData().get("num");
        }
        if (num == 0) {
            throw new BusinessException("修改文书失败,重新生成文书有误");
        }

    }

    /**
     * 【V1.11.4】描述： 修改移动端简案快办立案(处罚告知流程)相关文书
     *
     * @author: zhengqiang
     * @date: 2023/5/4
     * @param: modifyOfRegisterDto
     * @return {@link Result}
     **/
    @Transactional(rollbackFor = {Error.class, Exception.class})
    @Override
    public Result modifyAppFastCaseRegisterDocuments(AppFastCaseDocumentModifyOfRegisterDto modifyOfRegisterDto) {
        //立案审批表, 调查终结报告, 处罚告知审批表,处罚告知书, 不予处罚审批表及不予处罚告知书
        List ModifyKindCodeList = Arrays.asList(DocumentKindEnum.DOC_KIND_ZJBG.getCode(),
                DocumentKindEnum.DOC_KIND_CFGZSPB.getCode(), DocumentKindEnum.DOC_KIND_CFGZS.getCode(),
                DocumentKindEnum.DOC_KIND_DK1BYCFGZSPB.getCode(), DocumentKindEnum.DOC_KIND_DK2BYXZCFGZS.getCode());

        String caseId = modifyOfRegisterDto.getCaseId();
        //1.处理立案审批表
        FastCaseDocumentRecordModifyDto modifyDtoLASPB = modifyAppFastCaseRegisterData(modifyOfRegisterDto);
        modifyFastCaseDocumentRecord(modifyDtoLASPB);
        //查询需要修改的文书
        CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
        queryDto.setCaseId(caseId);
        List<CaseDocumentRecordDto> documentRecordDtoList = caseDocumentRecordService.getDocumentRecordDtoList(queryDto);
        if (ObjectUtil.isNotEmpty(documentRecordDtoList)) {
            for (CaseDocumentRecordDto recordDto : documentRecordDtoList) {
                String documentKindCode = recordDto.getDocumentKindCode();
                String documentCatalogCode = recordDto.getDocumentCatalogCode();
                FastCaseDocumentRecordModifyDto modifyDto = null;
                if (ModifyKindCodeList.contains(documentKindCode)) {
                    //重新生成涉及变动的文书
                    //调查终结报告, 处罚告知审批表, 不予处罚审批表及不予处罚告知书
                    modifyDto = buildDocumentModifyData(caseId, documentKindCode, documentCatalogCode);
                }
                if (ObjectUtil.isNotEmpty(modifyDto)) {
                    modifyFastCaseDocumentRecord(modifyDto);
                }
            }
        }
        return Result.success(Constant.STRING_SUCCESS_EN);
    }

    /**
     * 描述： 更新移动端立案相关数据
     *
     * @author: zhengqiang
     * @date: 2023/4/20
     * @param: saveDto
     * @return {@link boolean}
     **/
    private FastCaseDocumentRecordModifyDto modifyAppFastCaseRegisterData(AppFastCaseDocumentModifyOfRegisterDto modifyOfRegisterDto) {
        String caseId = modifyOfRegisterDto.getCaseId();

        //处理案由信息(违则,罚则可修改)
        //之前老数据更新为失效
        /*Example example = new Example(CaseReasonMainRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        List<CaseReasonMainRecord> recordList = caseReasonMainRecordMapper.selectByExample(example);
        if (recordList != null && recordList.size() > 0) {
            for (CaseReasonMainRecord record : recordList) {
                record.setStatus(Constant.STRING_0);
                caseReasonMainRecordMapper.updateByPrimaryKey(record);
            }
        }
        List<CaseReasonInfoDto> caseReasonInfoList = modifyOfRegisterDto.getCaseReasonInfoList();
        if (ObjectUtil.isNotEmpty(caseReasonInfoList)) {
            for (CaseReasonInfoDto caseReasonInfoDto : caseReasonInfoList) {
                CaseReasonMainRecord caseReasonMainRecord = new CaseReasonMainRecord();
                BeanUtils.copyProperties(caseReasonInfoDto, caseReasonMainRecord);
                caseReasonMainRecord.setCreateTime(LocalDateTime.now());
                caseReasonMainRecord.setId(BaseUtil.createUid());
                caseReasonMainRecord.setCaseId(caseId);
                caseReasonMainRecord.setCaseReasonNameSimple(BaseUtil.handleCaseReason(caseReasonInfoDto.getCaseReasonName()));
                caseReasonMainRecord.setIllegalBasisFormat(BaseUtil.removeHtml(caseReasonInfoDto.getIllegalBasis()));
                caseReasonMainRecord.setIllegalDetailFormat(BaseUtil.removeHtml(caseReasonInfoDto.getIllegalDetail()));
                caseReasonMainRecord.setPunishBasisFormat(BaseUtil.removeHtml(caseReasonInfoDto.getPunishBasis()));
                caseReasonMainRecord.setPunishDetailFormat(BaseUtil.removeHtml(caseReasonInfoDto.getPunishDetail()));
                caseReasonMainRecord.setStatus(Constant.STRING_1);
                String nodeIds = "";
                for (String str : caseReasonInfoDto.getCaseReasonIds()) {
                    if (org.apache.commons.lang.StringUtils.isEmpty(nodeIds)) {
                        nodeIds = str;
                    } else {
                        nodeIds = nodeIds + "," + str;
                    }
                }
                caseReasonMainRecord.setCaseReasonNodeid(nodeIds);
                caseReasonMainRecordMapper.insertSelective(caseReasonMainRecord);
            }
        }*/

        //更新主表数据 只能修改案件名称,案件名称
        CaseMainInfo caseMainInfo = new CaseMainInfo();
        caseMainInfo.setId(caseId);
        caseMainInfo.setCaseName(modifyOfRegisterDto.getCaseName());
        caseMainInfo.setCaseSource(modifyOfRegisterDto.getCaseSource());
        caseMainInfoMapper.updateByPrimaryKeySelective(caseMainInfo);

        //更新宽表数据 只能修改案件名称和案件简要情况,案发地址,发现时间
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        BeanUtils.copyProperties(modifyOfRegisterDto, updateCaseMainDetailInfo);
        CaseMainDetailInfo oldDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
        updateCaseMainDetailInfo.setCaseId(caseId);
        updateCaseMainDetailInfo.setId(oldDetailInfo.getId());
        updateCaseMainDetailInfo.setCaseName(modifyOfRegisterDto.getCaseName());
        updateCaseMainDetailInfo.setCaseConciseCondition(modifyOfRegisterDto.getCaseConciseCondition());
        caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);



        HashMap<String, Object> dataMap = BaseUtil.javaToMap(modifyOfRegisterDto);
        FastCaseDocumentRecordModifyDto modifyDto = new FastCaseDocumentRecordModifyDto();
        modifyDto.setDocumentId(modifyOfRegisterDto.getDocumentId());
        modifyDto.setDataMap(dataMap);
        return modifyDto;
    }


    /**
     * 【V1.12.1】描述： 生成简案快办告知书
     *
     * @author: zhengqiang
     * @date: 2023/8/17
     * @param: dto
     * @return {@link FastCaseNoticeDocumentVo}
     **/
    @Override
    public FastCaseNoticeDocumentVo createFastCaseNoticeDocument(FastCaseRegisterInfoQueryDto dto) {
        String caseId = dto.getCaseId();
        log.info("==> 生成简案快办告知书,入参：{}", caseId);
        CaseMainInfo oldCaseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        if (Objects.isNull(oldCaseMainInfo)) {
            throw new BusinessException("案件不存在");
        }

        // 查询业务关联文书配置
        ConfigBusiParamDocumentInfo configBusiParam = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(oldCaseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK2JAKBGZS.getCode());
        if (Objects.isNull(configBusiParam)) {
            throw new BusinessException("业务关联文书配置不存在");
        }
        String documentCatalogCode = configBusiParam.getDocumentCatalogCode();
        dto.setDocumentCatalogCode(documentCatalogCode);
        // 若已存在生成的文书直接查询返回
        FastCaseNoticeDocumentVo fastCaseNoticeDocument = getFastCaseNoticeDocument(dto);
        if (ObjectUtil.isNotEmpty(fastCaseNoticeDocument)) {
            return fastCaseNoticeDocument;
        }

        // 组装参数 生成文书
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        commonOperateSaveDto.setCaseId(caseId);
        commonOperateSaveDto.setDocumentCatalogCode(documentCatalogCode);
        commonOperateSaveDto.setIsUpdateRelationTable(Constant.STRING_0);

        HashMap<String,Object> dataMap = new HashMap<>(8);
        // 机构文书抬头标准名称
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(oldCaseMainInfo.getCaseOrgCode(), oldCaseMainInfo.getCaseDeptCode());
        dataMap.put("orgStandardName",sysDepartParam.getOrgStandardName());
        dataMap.put("signTime", "年      月      日");
        commonOperateSaveDto.setDataMap(dataMap);
        log.info("==> 文书生成公共方法start,入参{}", JSONUtil.toJsonStr(commonOperateSaveDto));
        Map<String, Object> docResultMap = stageDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
        log.info("==> 文书生成公共方法end,出参：{}", JSONUtil.toJsonStr(docResultMap));

        // 查询返回生成的文书url
        FastCaseNoticeDocumentVo newFastCaseNoticeDocument = getFastCaseNoticeDocument(dto);
        return newFastCaseNoticeDocument;
    }

    /**
     * 【V1.12.1】描述： 查询简案快办告知书
     *
     * @author: zhengqiang
     * @date: 2023/8/17
     * @param: dto
     * @return {@link FastCaseNoticeDocumentVo}
     **/
    private FastCaseNoticeDocumentVo getFastCaseNoticeDocument(FastCaseRegisterInfoQueryDto dto) {
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(dto.getCaseId(), dto.getDocumentCatalogCode());
        if (ObjectUtil.isNotEmpty(caseDocumentRecord)) {
            FastCaseNoticeDocumentVo documentVo = new FastCaseNoticeDocumentVo();
            BeanUtils.copyProperties(caseDocumentRecord, documentVo);
            documentVo.setDocumentId(caseDocumentRecord.getId());
            documentVo.setIsSign(YesOrNoEnum.NO.getCode());
            if (DocumentStatusEnum.CONFIRM_END.getCode().equals(caseDocumentRecord.getDocumentSignstampedStatus())) {
                documentVo.setIsSign(YesOrNoEnum.YES.getCode());
            }
            return documentVo;
        }
        return null;
    }

    /**
     * 【V1.12.1】描述： 快办告知步骤操作(上一步,下一步)
     *
     * @author: zhengqiang
     * @date: 2023/8/18
     * @param: operateDto
     * @return {@link int}
     **/
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public int saveFastInformOperateStep(FastCaseRegisterOperateDto operateDto) {
        String simpleFormType = null;
        if (StepOperateEnum.Next.getCode().equals(operateDto.getStepOperateType())) {
            simpleFormType = SimpleFormTypeEnum.EVIDENCE_COLLECTION.getCode();
        } else if (StepOperateEnum.Back.getCode().equals(operateDto.getStepOperateType())) {
            simpleFormType = SimpleFormTypeEnum.ITEM_SELECT.getCode();
        } else {
            throw new BusinessException("操作类型有误");
        }
        CaseMainDetailInfo updateCaseMainDetailInfo = new CaseMainDetailInfo();
        updateCaseMainDetailInfo.setCaseId(operateDto.getCaseId());
        updateCaseMainDetailInfo.setSimpleFormType(simpleFormType);
        return caseMainDetailInfoMapper.updateByPrimaryKeySelective(updateCaseMainDetailInfo);
    }

    /**
     * 【V1.12.1】描述： 获取自动结案提醒
     *
     * @author: zhengqiang
     * @date: 2023/8/23
     * @param: caseId
     * @return {@link FastAutoCloseCaseReminderVo}
     **/
    @Override
    public FastAutoCloseCaseReminderVo getAutoCloseCaseReminder(String caseId) {
        FastAutoCloseCaseReminderVo reminderVo = new FastAutoCloseCaseReminderVo();
        reminderVo.setIsAllowedAutoCloseCase(YesOrNoEnum.NO.getCode());
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        if (!CaseTypeEnum.FAST_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
            return reminderVo;
        }
        if (!CaseStageEnum.PUNISH_EXECUTION.getCode().equals(caseMainInfo.getCaseCurrentStageCode())) {
            return reminderVo;
        }

        //查询是否包含罚款
        boolean isHavePunishMoney = false;
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
        String punishKinds = caseMainDetailInfo.getPunishKinds();
        if (ObjectUtil.isNotEmpty(punishKinds) && (punishKinds.contains("罚款") || punishKinds.contains("没收违法所得"))) {
            isHavePunishMoney = true;
        }
        if (isHavePunishMoney) {
            //查询是否已缴款
            CasePaymentResultRecord casePaymentResult = casePaymentResultRecordService.getCasePaymentResultByCaseId(caseId);
            if (ObjectUtil.isEmpty(casePaymentResult)) {
                return reminderVo;
            }
            boolean isHaveZLGZ = false;
            //判断是否制作责令改正通知书
            CaseDocumentRecord ZLGZDocumentRecord = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode());
            if (ObjectUtil.isNotEmpty(ZLGZDocumentRecord)) {
                isHaveZLGZ = true;
            } else {
                //查询是否有上传责令改正通知书
                //1、查询案件关联文书
                List<CaseRelateDocumentInfoDto> caseRelateDocumentInfoList = caseRelatedDocumentRecordService.getCaseRelateDocumentInfoDto(caseId, DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode(), CaseStageEnum.INVESTIGATION.getCode());
                if (ObjectUtil.isNotEmpty(caseRelateDocumentInfoList)) {
                    isHaveZLGZ = true;
                }
                //2、查询线下文书
                List<CaseOfflineDocumentRecord> caseOfflineDocumentInfoList = caseOfflineDocumentRecordService.getCaseOfflineDocumentRecordByKindCodes(caseId, Arrays.asList(DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode()));
                if (ObjectUtil.isNotEmpty(caseOfflineDocumentInfoList)) {
                    isHaveZLGZ = true;
                }
            }

            if (isHaveZLGZ) {
                reminderVo.setIsAllowedAutoCloseCase(YesOrNoEnum.YES.getCode());
                reminderVo.setAutoCloseCaseReminder("当事人已完成整改且已缴款，满足自动结案条件，确定自动结案吗？");
            }

        } else {
            reminderVo.setIsAllowedAutoCloseCase(YesOrNoEnum.YES.getCode());
            reminderVo.setAutoCloseCaseReminder("本案件无罚款，满足自动结案条件确定自动结案吗？");
        }

        return reminderVo;
    }

    /**
     * 【V1.12.1】描述： 获取简案快办处罚事项
     *
     * @author: zhengqiang
     * @date: 2023/8/23
     * @param: orgCode
     * @return {@link List< PunishItemVo>}
     **/
    public List<PunishItemVo> getFastAuditPubishTreeByOrgCode(String orgCode) {
        List<PunishItemVo> auditPubishList = new ArrayList<>();
        //查询简案快办配置处罚事项
        List<ConfigFastCaseMattersVo> configFastCaseMattersVos = configFastCaseMattersService.getListByOrgCode(orgCode);
        if (ObjectUtil.isEmpty(configFastCaseMattersVos)) {
            return auditPubishList;
        }
        List<String> listCodes = configFastCaseMattersVos.stream().map(e -> e.getListCode()).collect(Collectors.toList());
        //查询事项库处罚事项
        Result auditPubishResult = regulatoryService.getAuditPubishTreeByOrgCode(orgCode);
        if (HttpStatus.HTTP_OK == auditPubishResult.getCode()) {
            List<PunishItemVo> punishItemVosNew = new ArrayList<>();
            List<PunishItemVo> punishItemVos = JSON.parseArray(auditPubishResult.getData().toString(), PunishItemVo.class);
            if (ObjectUtil.isEmpty(punishItemVos)) {
                return auditPubishList;
            }
            //过滤简案快办事项
            for (PunishItemVo punishItemVo : punishItemVos) {
                PunishItemVo punishItemVoNew = new PunishItemVo();
                List<PunishItemVo> childrensNew = new ArrayList<>();
                //获取子事项
                List<PunishItemVo> childrens = punishItemVo.getChildrens();
                if (ObjectUtil.isEmpty(childrens)) {
                    continue;
                }
                for (PunishItemVo children : childrens) {
                    //事项编码匹配
                    if (listCodes.contains(children.getNodeCode())) {
                        childrensNew.add(children);
                    }
                }
                if (ObjectUtil.isNotEmpty(childrensNew)) {
                    BeanUtils.copyProperties(punishItemVo, punishItemVoNew);
                    punishItemVoNew.setChildrens(childrensNew);
                }
                if (ObjectUtil.isNotEmpty(punishItemVoNew)) {
                    punishItemVosNew.add(punishItemVoNew);
                }
                return punishItemVosNew;
            }

        } else {
            throw new BusinessException("查询事项库处罚事项失败:" + auditPubishResult.getMessage());
        }

        return auditPubishList;
    }
}
